package com.lyy.blog.service;

import com.lyy.blog.dao.tagsrepositroy;
import com.lyy.blog.notfoundeexception;
import com.lyy.blog.po.blog;
import com.lyy.blog.po.tag;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
@Service
public class tagsserviceimpl implements tagsservice  {

    @Autowired
     private tagsrepositroy tagsrepositroy;

    @Transactional
    @Override
    public tag saveTag(tag tag) {
        return tagsrepositroy.save(tag);
    }

    @Transactional
    @Override
    public tag getTag(Long id) {
        return tagsrepositroy.getOne(id);
    }

    @Override
    public tag getTagByName(String name) {
        return tagsrepositroy.findByName(name);
    }
    @Transactional
    @Override
    public Page<tag> listTag(Pageable pageable) {
        return tagsrepositroy.findAll(pageable);
    }

    @Override
    public List<tag> listTag() {
        return tagsrepositroy.findAll();
    }

    @Override
    public List<tag> listTag(String ids) {
        return tagsrepositroy.findAllById(convertToList(ids));
    }

   //把字符串转化成数组
    private List<Long> convertToList(String ids) {
        List<Long> list = new ArrayList<>();
        if (!"".equals(ids) && ids != null) {
            String[] idarray = ids.split(",");
            for (int i=0; i < idarray.length;i++) {
                list.add(new Long(idarray[i]));
            }
        }
        return list;
    }

    @Transactional
    @Override
    public tag updateTag(Long id, tag tag) {
        tag t=tagsrepositroy.getOne(id);
        if(t==null){
            throw  new notfoundeexception("不存在这个标签");



        }
        //////这而不太明白
        BeanUtils.copyProperties(tag,t);
        return tagsrepositroy.save(t);
    }
    @Transactional
    @Override
    public void deleteTag(Long id) {
        tagsrepositroy.deleteById(id);

    }

    @Override
    public List<tag> listtag() {
        return tagsrepositroy.findAll();
    }

    @Override
    public List<tag> listtagtop(Integer size) {

        Pageable pageable= PageRequest.of(0,size, Sort.Direction.DESC,"blogs.size");
        return tagsrepositroy.findTop(pageable);
    }

}
